﻿Public Class FEditJob
    Private mJob As Entities.Backup.Job

    Private Const DefaultText As String = "Default"

    Private Sub FEditJob_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.Icon = My.Resources.harddisc_xp
    End Sub

    Public Shadows Sub Show(ByVal owner As IWin32Window, ByVal job As Entities.Backup.Job)
        mJob = job
        If job.Id = 0 Then
            Me.Text = "Create New Backup Job - Buddy 2 Buddy"
            job.Name = "New job"
        Else
            Me.Text = String.Format("{0} - Edit - Buddy 2 Buddy", job.Name)
        End If
        txtName.Text = job.Name
        txtComment.Text = job.Comment
        chkActive.Checked = job.Enabled

        Schedule_Set(job.Schedule)
        Source_Set(job.Source)
        Destination_Set(job.Destination, job.Id = 0)
        Encryption_Set(job.EncryptionProperties)
        Compression_Set(job.CompressionProperties)
        Inertia_Set(job.Inertia)
        Versioning_Set(job.Versioning)
        Actions_Set(job.Actions)
        MyBase.Show()
    End Sub

    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
        Try
            mJob.Name = txtName.Text
            mJob.Enabled = chkActive.Checked
            mJob.Comment = txtComment.Text

            mJob.Schedule = Schedule_Get()
            mJob.Source = Source_Get()
            mJob.Destination = Destination_Get()
            mJob.EncryptionProperties = Encryption_Get()
            mJob.CompressionProperties = Compression_Get()
            mJob.Destination = Destination_Get()
            mJob.Inertia = Inertia_Get()
            mJob.Versioning = Versioning_Get()
            mJob.NextRunUtc = EntityHandlers.Backup.Jobs.CalculateNextRunTime(mJob.Schedule)
            mJob.Actions = Actions_Get()
            EntityHandlers.Backup.Jobs.Save(mJob)
            Me.Close()
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub
    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub


#Region " Schedule "

    Private Sub Schedule_Set(ByVal schedule As Entities.Backup.SchduleBase)
        mSchedule_EventHandler_UpdateNextRuns_Disabled = True
        If TypeOf schedule Is Entities.Backup.RunOnChangeSchedule Then
            Dim clsS As Entities.Backup.RunOnChangeSchedule = CType(schedule, Entities.Backup.RunOnChangeSchedule)
            cboScheduleType.SelectedIndex = 0
        ElseIf TypeOf schedule Is Entities.Backup.HourlySchedule Then
            Dim clsS As Entities.Backup.HourlySchedule = CType(schedule, Entities.Backup.HourlySchedule)
            cboScheduleType.SelectedIndex = 1
        ElseIf TypeOf schedule Is Entities.Backup.DailySchedule Then
            Dim clsS As Entities.Backup.DailySchedule = CType(schedule, Entities.Backup.DailySchedule)
            cboScheduleType.SelectedIndex = 2
        ElseIf TypeOf schedule Is Entities.Backup.WeeklySchedule Then
            Dim clsS As Entities.Backup.WeeklySchedule = CType(schedule, Entities.Backup.WeeklySchedule)
            cboScheduleType.SelectedIndex = 3
            chkMonday.Checked = clsS.DaysToRunOn(0)
            chkTuesday.Checked = clsS.DaysToRunOn(1)
            chkWednesday.Checked = clsS.DaysToRunOn(2)
            chkThursday.Checked = clsS.DaysToRunOn(3)
            chkFriday.Checked = clsS.DaysToRunOn(4)
            chkSaturday.Checked = clsS.DaysToRunOn(5)
            chkSunday.Checked = clsS.DaysToRunOn(6)
        Else
            cboScheduleType.SelectedIndex = 0
        End If
        If schedule IsNot Nothing Then
            nudOffsetHours.Value = schedule.Offset.Hours
            nudOffsetMinutes.Value = schedule.Offset.Minutes
            nudOffsetSeconds.Value = schedule.Offset.Seconds
            chkRunMissedSchedulings.Checked = schedule.RunIfMissed
            mSchedule_EventHandler_UpdateNextRuns_Disabled = False
        End If
        Schedule_EventHandler_UpdateNextRuns()
    End Sub
    Private Function Schedule_Get() As Entities.Backup.SchduleBase
        Dim clsRet As Entities.Backup.SchduleBase
        Select Case cboScheduleType.SelectedIndex
            Case 0 'run on change
                clsRet = New Entities.Backup.RunOnChangeSchedule
                clsRet.Offset = New TimeSpan(CInt(nudOffsetHours.Value), CInt(nudOffsetMinutes.Value), CInt(nudOffsetSeconds.Value))
            Case 1 'every hour
                clsRet = New Entities.Backup.HourlySchedule
                clsRet.Offset = New TimeSpan(0, CInt(nudOffsetMinutes.Value), 0)
            Case 2 'every day
                clsRet = New Entities.Backup.DailySchedule
                clsRet.Offset = New TimeSpan(CInt(nudOffsetHours.Value), CInt(nudOffsetMinutes.Value), 0)
            Case 3 'every week
                clsRet = New Entities.Backup.WeeklySchedule
                clsRet.Offset = New TimeSpan(CInt(nudOffsetHours.Value), CInt(nudOffsetMinutes.Value), 0)
                With CType(clsRet, Entities.Backup.WeeklySchedule)
                    .DaysToRunOn(0) = chkMonday.Checked
                    .DaysToRunOn(1) = chkTuesday.Checked
                    .DaysToRunOn(2) = chkWednesday.Checked
                    .DaysToRunOn(3) = chkThursday.Checked
                    .DaysToRunOn(4) = chkFriday.Checked
                    .DaysToRunOn(5) = chkSaturday.Checked
                    .DaysToRunOn(6) = chkSunday.Checked
                End With
            Case Else
                Throw New NotImplementedException
        End Select
        clsRet.RunIfMissed = chkRunMissedSchedulings.Checked
        Return clsRet
    End Function

    Private Sub Schedule_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboScheduleType.SelectedIndexChanged
        Try
            Select Case cboScheduleType.SelectedIndex
                Case 0 'filewatch
                    Schedule_SetOffsetEnabled("Wait for", True, True, True)
                    Schedule_SetWeekdaysEnabled(False)
                Case 1 'hourly
                    Schedule_SetOffsetEnabled("Start at", False, True, False)
                    Schedule_SetWeekdaysEnabled(False)
                Case 2 'daily
                    Schedule_SetOffsetEnabled("Start at", True, True, False)
                    Schedule_SetWeekdaysEnabled(False)
                Case 3 'weekly
                    Schedule_SetOffsetEnabled("Start at", True, True, False)
                    Schedule_SetWeekdaysEnabled(True)
            End Select
            Schedule_EventHandler_UpdateNextRuns()
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub
    Private Sub Schedule_SetWeekdaysEnabled(ByVal enable As Boolean)
        chkMonday.Enabled = enable : chkTuesday.Enabled = enable : chkWednesday.Enabled = enable
        chkThursday.Enabled = enable : chkFriday.Enabled = enable
        chkSaturday.Enabled = enable : chkSunday.Enabled = enable
    End Sub
    Private Sub Schedule_SetOffsetEnabled(ByVal label As String, ByVal h As Boolean, ByVal m As Boolean, ByVal s As Boolean)
        lblOffset.Text = label
        nudOffsetHours.Enabled = h
        nudOffsetMinutes.Enabled = m
        nudOffsetSeconds.Enabled = s
    End Sub
    Private mSchedule_EventHandler_UpdateNextRuns_Disabled As Boolean = False
    Private Sub Schedule_EventHandler_UpdateNextRuns()
        Try
            If mSchedule_EventHandler_UpdateNextRuns_Disabled Then Return

            Dim clsSchedule As Entities.Backup.SchduleBase = Schedule_Get()
            Dim strText As String = "Unknown"
            If clsSchedule.HasKnownNextRunTime Then
                Dim dtNext As Date = EntityHandlers.Backup.Jobs.CalculateNextRunTime(clsSchedule)
                If dtNext <> DateTime.MaxValue Then
                    Dim clsSB As New System.Text.StringBuilder
                    For i As Integer = 1 To 10
                        clsSB.AppendLine(dtNext.ToLocalTime.ToString("g"))
                        dtNext = EntityHandlers.Backup.Jobs.CalculateNextRunTime(clsSchedule, dtNext.AddSeconds(1))
                    Next
                    strText = clsSB.ToString
                End If
            End If
            txtNextTwoRuns.Text = strText
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

    Private Sub nudOffsetHours_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nudOffsetHours.ValueChanged
        Schedule_EventHandler_UpdateNextRuns()
    End Sub
    Private Sub nudOffsetMinutes_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nudOffsetMinutes.ValueChanged
        Schedule_EventHandler_UpdateNextRuns()
    End Sub
    Private Sub nudOffsetSeconds_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nudOffsetSeconds.ValueChanged
        Schedule_EventHandler_UpdateNextRuns()
    End Sub
    Private Sub chkMonday_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkMonday.CheckedChanged
        Schedule_EventHandler_UpdateNextRuns()
    End Sub
    Private Sub chkTuesday_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkTuesday.CheckedChanged
        Schedule_EventHandler_UpdateNextRuns()
    End Sub
    Private Sub chkWednesday_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkWednesday.CheckedChanged
        Schedule_EventHandler_UpdateNextRuns()
    End Sub
    Private Sub chkThursday_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkThursday.CheckedChanged
        Schedule_EventHandler_UpdateNextRuns()
    End Sub
    Private Sub chkFriday_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkFriday.CheckedChanged
        Schedule_EventHandler_UpdateNextRuns()
    End Sub
    Private Sub chkSaturday_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkSaturday.CheckedChanged
        Schedule_EventHandler_UpdateNextRuns()
    End Sub
    Private Sub chkSunday_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkSunday.CheckedChanged
        Schedule_EventHandler_UpdateNextRuns()
    End Sub


#End Region

#Region " Source "
    Private Sub Source_Set(ByVal source As Entities.Backup.Source)
        If source Is Nothing Then Return
        If source.Folders IsNot Nothing Then
            lvwLocalFolders.BeginUpdate()
            For Each clsFolder As Entities.Backup.SourceFolder In source.Folders
                Dim clsItem As New ListViewItem
                Source_UpdateSourceFolder(clsItem, clsFolder)
                lvwLocalFolders.Items.Add(clsItem)
            Next
            lvwLocalFolders.Sort()
            lvwLocalFolders.EndUpdate()
        End If
        FileFilterControl1.SetFilter(source.Filter)
    End Sub
    Private Sub Source_UpdateSourceFolder(ByVal item As ListViewItem, ByVal folder As Entities.Backup.SourceFolder)
        With item
            .SubItems.Clear()
            .Text = folder.Path
            If folder.CustomFilter IsNot Nothing Then
                .SubItems.Add(MatchPatternsToString(folder.CustomFilter.IncludePatterns))
                .SubItems.Add(MatchPatternsToString(folder.CustomFilter.ExcludePatterns))
                .SubItems.Add(Source_BoolToClearText(folder.CustomFilter.ClearFileArchiveFlag))
                .SubItems.Add(Source_BoolToIncludeText(folder.CustomFilter.IncludeHiddenFiles))
                .SubItems.Add(Source_BoolToIncludeText(folder.CustomFilter.IncludeSystemFiles))
            Else
                .SubItems.Add(DefaultText)
                .SubItems.Add(DefaultText)
                .SubItems.Add(DefaultText)
                .SubItems.Add(DefaultText)
                .SubItems.Add(DefaultText)
            End If
            .Tag = folder
        End With
    End Sub
    Private Function MatchPatternsToString(ByVal patterns As Generic.List(Of Entities.MatchPattern)) As String
        If patterns Is Nothing Then Return DefaultText
        If patterns.Count = 0 Then Return DefaultText
        Dim clsSB As New System.Text.StringBuilder
        For Each clsPat As Entities.MatchPattern In patterns
            If clsSB.Length > 0 Then clsSB.Append(", ")
            clsSB.Append(clsPat.Pattern)
        Next
        Return clsSB.ToString
    End Function
    Private Function Source_BoolToIncludeText(ByVal value As Nullable(Of Boolean)) As String
        Return Source_BoolToText(value, "Include", "Exclude", DefaultText)
    End Function
    Private Function Source_BoolToClearText(ByVal value As Nullable(Of Boolean)) As String
        Return Source_BoolToText(value, "Clear", "Leave", DefaultText)
    End Function
    Private Function Source_BoolToText(ByVal value As Nullable(Of Boolean), ByVal trueText As String, ByVal falseText As String, ByVal nullText As String) As String
        If Not value.HasValue Then
            Return nullText
        ElseIf value.Value Then
            Return trueText
        Else
            Return falseText
        End If
    End Function
    Private Function Source_Get() As Entities.Backup.Source
        Dim clsRet As New Entities.Backup.Source
        clsRet.Folders = New Generic.List(Of Entities.Backup.SourceFolder)
        For Each clsItem As ListViewItem In lvwLocalFolders.Items
            Dim clsFolder As Entities.Backup.SourceFolder
            clsFolder = CType(clsItem.Tag, Entities.Backup.SourceFolder)
            clsRet.Folders.Add(clsFolder)
        Next
        clsRet.Filter = FileFilterControl1.GetFilter
        Return clsRet
    End Function

    Private Sub Source_Clear(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSourceClear.Click
        lvwLocalFolders.Items.Clear()
    End Sub
    Private Sub Source_Remove(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSourceRemove.Click
        While lvwLocalFolders.SelectedItems.Count > 0
            lvwLocalFolders.SelectedItems(0).Remove()
        End While
    End Sub
    Private Sub Source_Add(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSourceAdd.Click
        Try
            With FolderBrowserDialog1
                .RootFolder = Environment.SpecialFolder.MyComputer
                .ShowNewFolderButton = True
                .Description = "Select folder to backup"
                Select Case .ShowDialog
                    Case Windows.Forms.DialogResult.OK
                        Dim clsSourceFolder As New Entities.Backup.SourceFolder
                        clsSourceFolder.Path = .SelectedPath
                        clsSourceFolder.Recursive = True
                        Dim clsItem As New ListViewItem
                        Source_UpdateSourceFolder(clsItem, clsSourceFolder)
                        lvwLocalFolders.Items.Add(clsItem)
                End Select
            End With
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub
    Private Sub Source_EditFolderFilter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSourceEditFilter.Click
        Try
            If lvwLocalFolders.SelectedItems.Count <> 1 Then Beep() : Return
            Dim clsItem As ListViewItem = lvwLocalFolders.SelectedItems(0)
            Dim clsFolder As Entities.Backup.SourceFolder
            clsFolder = CType(clsItem.Tag, Entities.Backup.SourceFolder)

            Dim clsRes As Entities.Backup.FileFilter

            Dim clsView As New FEditSourceFolderFilter
            clsRes = clsView.ShowDialog(Me, clsFolder.CustomFilter)
            If clsRes IsNot Nothing Then
                clsFolder.CustomFilter = clsRes
                Source_UpdateSourceFolder(clsItem, clsFolder)
            End If
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

#End Region

#Region " Encryption "

    Private Sub Encryption_Set(ByVal prop As Entities.Backup.EncryptionProperties)
        If prop Is Nothing Then
            cboEncryptionMethod.SelectedIndex = 1
            txtPassword.Text = Nothing
        Else
            Select Case prop.Type
                Case Entities.Backup.EncryptionType.None
                    cboEncryptionMethod.SelectedIndex = 0
                Case Entities.Backup.EncryptionType.Rijndael
                    cboEncryptionMethod.SelectedIndex = 1
            End Select
            txtPassword.Text = prop.Password
        End If
    End Sub
    Private Function Encryption_Get() As Entities.Backup.EncryptionProperties
        Dim clsRet As New Entities.Backup.EncryptionProperties
        Select Case cboEncryptionMethod.SelectedIndex
            Case 0 'none
                clsRet.Type = Entities.Backup.EncryptionType.None
                clsRet.Password = Nothing
            Case 1 'rijndael
                clsRet.Type = Entities.Backup.EncryptionType.Rijndael
                clsRet.Password = txtPassword.Text
        End Select
        Return clsRet
    End Function

    Private Sub Encryption_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboEncryptionMethod.SelectedIndexChanged
        Try
            Select Case cboEncryptionMethod.SelectedIndex
                Case 0 'none
                    txtPassword.Enabled = False
                Case 1 'rijndael
                    txtPassword.Enabled = True
            End Select
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

#End Region

#Region " Destination "
    Private Sub Destination_Set(ByVal destination As Entities.Backup.Destination, ByVal isNewJob As Boolean)
        If destination IsNot Nothing Then
            If destination.ContractIds IsNot Nothing Then
                For Each iContractId As Integer In destination.ContractIds
                    Dim clsContract As Entities.Backup.ReceivedContract
                    clsContract = EntityHandlers.Backup.ReceivedContracts.GetById(iContractId)
                    Destination_AddContract(clsContract)
                Next
            End If
        End If
    End Sub
    Private Function Destination_Get() As Entities.Backup.Destination
        Dim clsRet As New Entities.Backup.Destination
        clsRet.ContractIds = New Generic.List(Of Integer)
        For Each clsItem As ListViewItem In lvwContracts.Items
            Dim clsCon As Entities.Backup.ReceivedContract = CType(clsItem.Tag, Entities.Backup.ReceivedContract)
            clsRet.ContractIds.Add(clsCon.Id)
        Next
        Return clsRet
    End Function
    Private Sub Destination_AddContract(ByVal contract As Entities.Backup.ReceivedContract)
        Dim clsBuddy As Entities.Buddy = Framework.Buddies.Manager.GetById(contract.IssuedByBuddyId)
        With lvwContracts.Items.Add(clsBuddy.NameLocal)
            .SubItems.Add(Framework.Misc.ToReadableFileSize(contract.StorageSize))
            .SubItems.Add(contract.Comment)
            .Tag = contract
        End With
    End Sub
    Private Function Destination_GetContracts() As Generic.List(Of Entities.Backup.ReceivedContract)
        Dim aRet As New Generic.List(Of Entities.Backup.ReceivedContract)
        For Each clsItem As ListViewItem In lvwContracts.Items
            Dim clsCon As Entities.Backup.ReceivedContract = CType(clsItem.Tag, Entities.Backup.ReceivedContract)
            aRet.Add(clsCon)
        Next
        Return aRet
    End Function

    Private Sub Destination_RemoveContract(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemoveContract.Click
        While lvwContracts.SelectedItems.Count > 0
            lvwContracts.SelectedItems(0).Remove()
        End While
    End Sub
    Private Sub Destination_ClearContracts(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClearContracts.Click
        lvwContracts.Items.Clear()
    End Sub
    Private Sub Destination_AddContract(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddContract.Click
        Try
            Dim clsView As New FSelectContract
            Dim aNew As Generic.List(Of Entities.Backup.ReceivedContract)
            aNew = clsView.ShowDialog(Me, Destination_GetContracts)
            If aNew IsNot Nothing Then
                For Each clsCon As Entities.Backup.ReceivedContract In aNew
                    Destination_AddContract(clsCon)
                Next
            End If
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

#End Region

#Region " Compression "
    Private Sub Compression_Set(ByVal props As Entities.Backup.CompressionProperties)
        If props Is Nothing Then
            cboCompression.SelectedIndex = 1
        Else
            Select Case props.Type
                Case Entities.Backup.CompressionType.None
                    cboCompression.SelectedIndex = 0
                Case Entities.Backup.CompressionType.LZMA
                    cboCompression.SelectedIndex = 1
                Case Else
                    Throw New NotImplementedException
            End Select
        End If
    End Sub
    Private Function Compression_Get() As Entities.Backup.CompressionProperties
        Dim clsRet As New Entities.Backup.CompressionProperties
        Select Case cboCompression.SelectedIndex
            Case 0
                clsRet.Type = Entities.Backup.CompressionType.None
            Case 1
                clsRet.Type = Entities.Backup.CompressionType.LZMA
                clsRet.Level = Entities.Backup.CompressionLevel.Normal
            Case Else
                Throw New NotImplementedException
        End Select
        Return clsRet
    End Function

  

#End Region

#Region " Inertia "
    Private Sub Inertia_Set(ByVal inertia As Entities.Backup.Inertia)
        If inertia IsNot Nothing Then
            chkUseInertia.Checked = inertia.Use
            If inertia.ChangedTrigger IsNot Nothing Then
                chkUseInertiaOnChangedFiles.Checked = True
                nudChangedFileCount.Value = inertia.ChangedTrigger.FileCount
                nudChangedFileSharePercentage.Value = inertia.ChangedTrigger.FilePercentageShare
            End If
            If inertia.CreatedOrDeletedTrigger IsNot Nothing Then
                chkUseInertiaOnAddedOrDeleted.Checked = True
                nudAddedDeletedFileCount.Value = inertia.CreatedOrDeletedTrigger.FileCount
                nudAddedDeletedFileSharePercentage.Value = inertia.CreatedOrDeletedTrigger.FilePercentageShare
            End If
            chkInertia_OverridenNextRun.Checked = inertia.OverridenNextRun
        End If
    End Sub
    Private Function Inertia_Get() As Entities.Backup.Inertia
        Dim clsRet As New Entities.Backup.Inertia
        If chkUseInertia.Checked Then
            clsRet.Use = True
            If chkUseInertiaOnAddedOrDeleted.Checked Then
                clsRet.CreatedOrDeletedTrigger = New Entities.Backup.InertiaTrigger
                clsRet.CreatedOrDeletedTrigger.FileCount = CInt(nudAddedDeletedFileCount.Value)
                clsRet.CreatedOrDeletedTrigger.FilePercentageShare = CByte(nudAddedDeletedFileSharePercentage.Value)
            End If
            If chkUseInertiaOnChangedFiles.Checked Then
                clsRet.ChangedTrigger = New Entities.Backup.InertiaTrigger
                clsRet.ChangedTrigger.FileCount = CInt(nudChangedFileCount.Value)
                clsRet.ChangedTrigger.FilePercentageShare = CByte(nudChangedFileSharePercentage.Value)
            End If
            clsRet.OverridenNextRun = chkInertia_OverridenNextRun.Checked
        End If
        Return clsRet
    End Function

    Private Sub chkUseInertia_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkUseInertia.CheckedChanged
        Try
            Dim blnEnable As Boolean = chkUseInertia.Checked

            chkUseInertiaOnAddedOrDeleted.Enabled = blnEnable
            chkUseInertiaOnChangedFiles.Enabled = blnEnable
            nudAddedDeletedFileCount.Enabled = blnEnable And chkUseInertiaOnAddedOrDeleted.Checked
            nudAddedDeletedFileSharePercentage.Enabled = blnEnable And chkUseInertiaOnAddedOrDeleted.Checked
            nudChangedFileCount.Enabled = blnEnable And chkUseInertiaOnChangedFiles.Checked
            nudChangedFileSharePercentage.Enabled = blnEnable And chkUseInertiaOnChangedFiles.Checked
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

    Private Sub chkUseInertiaOnAddedOrDeleted_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkUseInertiaOnAddedOrDeleted.CheckedChanged
        Try
            Dim blnEnable As Boolean = chkUseInertia.Checked And chkUseInertiaOnAddedOrDeleted.Checked
            nudAddedDeletedFileCount.Enabled = blnEnable
            nudAddedDeletedFileSharePercentage.Enabled = blnEnable
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

    Private Sub chkUseInertiaOnChangedFiles_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkUseInertiaOnChangedFiles.CheckedChanged
        Try
            Dim blnEnable As Boolean = chkUseInertia.Checked And chkUseInertiaOnChangedFiles.Checked
            nudChangedFileCount.Enabled = blnEnable
            nudChangedFileSharePercentage.Enabled = blnEnable
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub
#End Region

#Region " Versioning "

    Private Sub Versioning_Set(ByVal versioning As Entities.Backup.Versioning)
        If versioning IsNot Nothing Then
            chkUseVersioning.Checked = versioning.KeepOldVersions
            nudVersionsToKeep.Value = versioning.VersionsToKeep
            chkUseVersioning_RemoveAfter.Checked = versioning.PurgeOldVersions
            nudVersioningRemoveAfterDays.Value = versioning.PurgeOldVersionsAfterDays
            chkOnlyKeepDeletedFiles.Checked = versioning.KeepDeletedFilesOnly
            chkUseVersioning.Checked = False
        End If
    End Sub
    Private Function Versioning_Get() As Entities.Backup.Versioning
        Dim clsRet As New Entities.Backup.Versioning
        clsRet.KeepOldVersions = chkUseVersioning.Checked
        clsRet.VersionsToKeep = CInt(nudVersionsToKeep.Value)
        clsRet.PurgeOldVersions = chkUseVersioning_RemoveAfter.Checked
        clsRet.PurgeOldVersionsAfterDays = CInt(nudVersioningRemoveAfterDays.Value)
        clsRet.KeepOldVersions = chkOnlyKeepDeletedFiles.Checked
        Return clsRet
    End Function
    Private Sub chkUseVersioning_RemoveAfter_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkUseVersioning_RemoveAfter.CheckedChanged
        nudVersioningRemoveAfterDays.Enabled = chkUseVersioning_RemoveAfter.Checked
    End Sub

    Private Sub chkUseVersioning_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkUseVersioning.CheckedChanged
        chkUseVersioning_RemoveAfter.Enabled = chkUseVersioning.Checked
        nudVersionsToKeep.Enabled = chkUseVersioning.Checked And Not chkOnlyKeepDeletedFiles.Checked
        nudVersioningRemoveAfterDays.Enabled = chkUseVersioning.Checked And chkUseVersioning_RemoveAfter.Checked
        chkOnlyKeepDeletedFiles.Enabled = chkUseVersioning.Checked
    End Sub

    Private Sub chkOnlyKeepDeletedFiles_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkOnlyKeepDeletedFiles.CheckedChanged
        If chkOnlyKeepDeletedFiles.Checked Then
            nudVersionsToKeep.Value = 1
            nudVersionsToKeep.Enabled = False
        Else
            nudVersionsToKeep.Enabled = True
        End If
    End Sub

#End Region

#Region " Actions "
    Private Function Actions_Get() As Entities.Backup.Actions
        Dim clsRet As New Entities.Backup.Actions
        clsRet.OnCompletion = Actions_GetCompletion
        clsRet.OnFail = Actions_GetFail()
        clsRet.OnError = Actions_GetError()
        Return clsRet
    End Function
    Private Function Actions_GetCompletion() As Entities.Backup.CompletionAction
        Dim clsRet As New Entities.Backup.CompletionAction
        Actions_FillEndAction(clsRet, chkActionComplete_SendEmail _
                                    , chkActionComplete_CustomEmailAddress _
                                    , txtActionComplete_CustomEmailAdress _
                                    , chkActionComplete_ShowTrayNotification _
                                    , chkActionComplete_Deactivate)
        Return clsRet
    End Function
    Private Function Actions_GetError() As Entities.Backup.ErrorAction
        Dim clsRet As New Entities.Backup.ErrorAction
        Actions_FillActionBase(clsRet, chkActionError_SendEmail _
                                     , chkActionError_CustomEmailAddress _
                                     , txtActionError_CustomEmailAdress _
                                     , chkActionError_ShowTrayNotification)
        clsRet.RetryBeforeFailing = chkActionError_Retry.Checked
        clsRet.RetryCount = CShort(nudActionError_RetryCount.Value)
        clsRet.RetryDelayInSeconds = CInt(nudActionError_RetryDelay.Value)
        Return clsRet
    End Function
    Private Function Actions_GetFail() As Entities.Backup.FailAction
        Dim clsRet As New Entities.Backup.FailAction
        Actions_FillEndAction(clsRet, chkActionFail_SendEmail _
                                    , chkActionFail_CustomEmailAddress _
                                    , txtActionFail_CustomEmailAdress _
                                    , chkActionFail_ShowTrayNotification _
                                    , chkActionFail_DeactivateJob)
        Return clsRet
    End Function
    Private Sub Actions_FillEndAction(ByVal action As Entities.Backup.EndActionBase, ByVal checkEmail As CheckBox, ByVal checkCustomEmail As CheckBox, ByVal email As TextBox, ByVal checkTray As CheckBox, ByVal checkDeactivateJob As CheckBox)
        Actions_FillActionBase(action, checkEmail, checkCustomEmail, email, checkTray)
        action.DeactivateJob = checkDeactivateJob.Checked
    End Sub
    Private Sub Actions_FillActionBase(ByVal action As Entities.Backup.ActionBase, ByVal checkEmail As CheckBox, ByVal checkCustomEmail As CheckBox, ByVal email As TextBox, ByVal checkTray As CheckBox)
        action.SendEmail = checkEmail.Checked
        action.CustomEmail = checkCustomEmail.Checked
        action.CustomEmailAddress = email.Text
        action.ShowTrayNotification = checkTray.Checked
    End Sub

    Private Sub Actions_Set(ByVal actions As Entities.Backup.Actions)
        Dim clsComplete As Entities.Backup.CompletionAction = Nothing
        Dim clsError As Entities.Backup.ErrorAction = Nothing
        Dim clsFail As Entities.Backup.FailAction = Nothing
        If actions IsNot Nothing Then
            clsComplete = actions.OnCompletion
            clsError = actions.OnError
            clsFail = actions.OnFail
        End If
        Actions_SetEndAction(clsComplete, chkActionComplete_SendEmail _
                                        , chkActionComplete_CustomEmailAddress _
                                        , txtActionComplete_CustomEmailAdress _
                                        , chkActionComplete_ShowTrayNotification _
                                        , chkActionComplete_Deactivate)
        Actions_SetActionBase(clsError, chkActionError_SendEmail _
                                      , chkActionError_CustomEmailAddress _
                                      , txtActionError_CustomEmailAdress _
                                      , chkActionError_ShowTrayNotification)
        Actions_SetEndAction(clsFail, chkActionFail_SendEmail _
                                    , chkActionFail_CustomEmailAddress _
                                    , txtActionFail_CustomEmailAdress _
                                    , chkActionFail_ShowTrayNotification _
                                    , chkActionFail_DeactivateJob)
        If clsError IsNot Nothing Then
            chkActionError_Retry.Checked = clsError.RetryBeforeFailing
            nudActionError_RetryCount.Value = clsError.RetryCount
            nudActionError_RetryDelay.Value = clsError.RetryDelayInSeconds
        Else
            chkActionError_Retry.Checked = True
            nudActionError_RetryCount.Value = 5
            nudActionError_RetryDelay.Value = 5 * 60
        End If
    End Sub

    Private Sub Actions_SetEndAction(ByVal action As Entities.Backup.EndActionBase, ByVal checkEmail As CheckBox, ByVal checkCustomEmail As CheckBox, ByVal email As TextBox, ByVal tray As CheckBox, ByVal deactivate As CheckBox)
        If action IsNot Nothing Then
            deactivate.Checked = action.DeactivateJob
        End If
        Actions_SetActionBase(action, checkEmail, checkCustomEmail, email, tray)
    End Sub

    Private Sub Actions_SetActionBase(ByVal action As Entities.Backup.ActionBase, ByVal checkEmail As CheckBox, ByVal checkCustomEmail As CheckBox, ByVal email As TextBox, ByVal tray As CheckBox)
        If action Is Nothing Then
            checkEmail.Checked = True
            checkCustomEmail.Checked = False
            tray.Checked = True
            email.Text = Nothing
        Else
            checkEmail.Checked = action.SendEmail
            checkCustomEmail.Checked = action.CustomEmail
            email.Text = action.CustomEmailAddress
            tray.Checked = action.ShowTrayNotification
        End If
    End Sub
    Private Sub chkActionError_Retry_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkActionError_Retry.CheckedChanged
        nudActionError_RetryCount.Enabled = chkActionError_Retry.Checked
        nudActionError_RetryDelay.Enabled = chkActionError_Retry.Checked
    End Sub

    Private Sub chkActionError_SendEmail_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkActionError_SendEmail.CheckedChanged
        chkActionError_CustomEmailAddress.Enabled = chkActionError_SendEmail.Checked
        txtActionError_CustomEmailAdress.Enabled = chkActionError_CustomEmailAddress.Checked And chkActionError_SendEmail.Checked
    End Sub

    Private Sub chkActionError_CustomEmailAddress_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkActionError_CustomEmailAddress.CheckedChanged
        txtActionError_CustomEmailAdress.Enabled = chkActionError_CustomEmailAddress.Checked
    End Sub

    Private Sub chkActionComplete_CustomEmailAddress_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkActionComplete_CustomEmailAddress.CheckedChanged
        txtActionComplete_CustomEmailAdress.Enabled = chkActionComplete_CustomEmailAddress.Checked
    End Sub

    Private Sub chkActionComplete_SendEmail_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkActionComplete_SendEmail.CheckedChanged
        chkActionComplete_CustomEmailAddress.Enabled = chkActionComplete_SendEmail.Checked
        txtActionComplete_CustomEmailAdress.Enabled = chkActionComplete_CustomEmailAddress.Checked And chkActionComplete_SendEmail.Checked
    End Sub

    Private Sub chkActionFail_CustomEmailAddress_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkActionFail_CustomEmailAddress.CheckedChanged
        txtActionFail_CustomEmailAdress.Enabled = chkActionFail_CustomEmailAddress.Checked
    End Sub

    Private Sub chkActionFail_SendEmail_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkActionFail_SendEmail.CheckedChanged
        chkActionFail_CustomEmailAddress.Enabled = chkActionFail_SendEmail.Checked
        txtActionFail_CustomEmailAdress.Enabled = chkActionFail_CustomEmailAddress.Checked And chkActionFail_SendEmail.Checked
    End Sub


#End Region

End Class
